import React, {FC, useEffect, useMemo, useState} from 'react'
import {Modal, Table, Pagination, Form, Input, message} from 'antd'
import SearchForm from '@/components/SearchForm'
import {DirverClounms} from '../../driver/constant'
import {ManagerColnums, OperationDriverType} from '../constant'
import {getPageByAdmin} from '@/service/customer/driver'
import {
	fleetAdminAddDriver,
	getFleetAdminList,
	fleetAdminMoverDriver,
} from '@/service/customer/fleet'

interface DriverModalType {
	driverModalVisivle: boolean
	setdriverModalVisivle: (visible: boolean) => void
	fleetAdminRecord: Record<string, string>
	callBack?: () => void
	operationDriver: any
	fleetId: string
}

const OperationDriverMap: Record<any, string> = {
	[OperationDriverType.Add]: '添加',
	[OperationDriverType.Transfer]: '迁移',
	[OperationDriverType.Edit]: '编辑',
}

const driverModal: FC<DriverModalType> = ({
	driverModalVisivle,
	setdriverModalVisivle,
	operationDriver,
	fleetAdminRecord,
	callBack,
}) => {
	const [saveLoading, setSaveLoading] = useState(false)
	const [loading, setLoading] = useState(false)
	const [dataList, setDataList] = useState<any[]>([])
	const [pagination, setPagination] = useState({
		current: 1,
		pageSize: 10,
	})
	const [total, setTotal] = useState(0)
	const [selectedRow, setSelectedRow] = useState<any[]>([])
	const [selectedKeys, setSelectedKeys] = useState<any[]>([])
	const [dirverModalForm] = Form.useForm()
	const [visible, setVisible] = useState(false)
	const [mangerLoading] = useState(false)
	const [mangerDataList, setMangerDataList] = useState<any[]>([])
	const [mangerPagination, setMangerPagination] = useState({
		current: 1,
		pageSize: 10,
	})
	const [mangertotal, setMangertotal] = useState(0)
	const [mangerSelectedRow, setMangerSelectedRow] = useState<any>([])
	const [FormData, setFormData] = useState({})
	const [searchData, setSearchData] = useState<any>({})

	const FleetFormItems: any[] = useMemo(
		() => [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						key: 'name',
						name: 'name',
						label: '司机名称',
					},
					{
						type: 'input',
						key: 'tel',
						name: 'tel',
						label: '司机手机号',
					},
					{
						type: 'input',
						key: 'idNo',
						name: 'idNo',
						label: '司机身份证号',
					},
				],
			},
		],
		[],
	)

	const Cloums: any[] = useMemo(() => [...DirverClounms], [])

	// 获取司管员列表
	const getMangrData = async () => {
		setLoading(true)
		const obj = {
			...searchData,
			current: mangerPagination.current,
			size: mangerPagination.pageSize,
			isNeedOrg: 1,
		}
		const data = await getFleetAdminList(obj).catch(() => setLoading(false))
		if (data.code === 0) {
			setMangerDataList(data.data.records)
			setMangertotal(data.data.total)
		}
		setLoading(false)
	}

	useEffect(() => {
		if (!visible) return
		getMangrData()
	}, [visible])

	useEffect(() => {
		getMangrData()
	}, [mangerPagination])

	// 获取司机列表
	const getData = async (params?: any) => {
		const obj = {
			current: pagination.current,
			size: pagination.pageSize,
			...params,
		}

		if (operationDriver === OperationDriverType.Transfer) {
			obj.adminId = fleetAdminRecord.id
		} else {
			obj.addAdminDriver = 1
		}

		setLoading(true)

		const data = await getPageByAdmin(obj).catch(() => setLoading(false))
		if (data.code === 0) {
			setDataList(data.data.records)
			setTotal(data.data.total)
		}
		setLoading(false)
	}

	useEffect(() => {
		if (!driverModalVisivle) return
		setDataList([])
		setSelectedRow([])
		setSelectedKeys([])
		dirverModalForm.resetFields()
		getData()
		setFormData({})
		setMangerPagination({
			current: 1,
			pageSize: 10,
		})
		setPagination({
			current: 1,
			pageSize: 10,
		})
	}, [driverModalVisivle])

	// 司管员保存,和司官员迁移
	const onSave = async () => {
		try {
			if (selectedRow.length === 0) {
				message.error('请选择司机')
				return
			}
			if (operationDriver === OperationDriverType.Transfer) {
				const formData = await dirverModalForm.validateFields()
				const data = await fleetAdminMoverDriver({
					adminId: formData.id,
					ids: selectedRow.map((item) => item.driverId).join(','),
				}).catch(() => setSaveLoading(false))
				if (data.code === 0) {
					message.success('迁移成功')
					callBack?.()
					setMangerPagination({
						current: 1,
						pageSize: 10,
					})
					setPagination({
						current: 1,
						pageSize: 10,
					})

					setdriverModalVisivle(false)
				} else {
					message.error('迁移失败')
				}
				setSaveLoading(false)
			} else {
				setSaveLoading(true)
				const data = await fleetAdminAddDriver({
					ids: selectedRow.map((item) => item.driverId).join(','),
					adminId: fleetAdminRecord.id,
				}).catch(() => setSaveLoading(false))
				if (data.code === 0) {
					message.success('添加成功')
					callBack?.()
					setMangerPagination({
						current: 1,
						pageSize: 10,
					})
					setPagination({
						current: 1,
						pageSize: 10,
					})
					setdriverModalVisivle(false)
				} else {
					message.error('添加失败')
				}
				setSaveLoading(false)
			}
		} catch (error) {
			setSaveLoading(false)
		}
	}

	const onMangerSave = () => {
		dirverModalForm.setFieldsValue({
			name: mangerSelectedRow.name,
			id: mangerSelectedRow.id,
		})
		setVisible(false)
	}

	const paginationChange = (current: number, pageSize: number) => {
		setPagination({
			current,
			pageSize,
		})
		getData({...FormData, ...{current, size: pageSize}})
	}

	const FormItems: any[] = useMemo(
		() => [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						key: 'name',
						name: 'name',
						label: '司管员名称',
					},
					{
						type: 'input',
						key: 'id',
						name: 'id',
						label: '司管员id',
					},
					{},
				],
			},
		],
		[],
	)

	return (
		<div>
			<Modal
				title="选择司管员"
				open={visible}
				onCancel={() => {
					setVisible(false)
				}}
				width={1000}
				onOk={onMangerSave}
				zIndex={2}>
				<div className="addVehicleInfo">
					<div className="searchBox">
						<SearchForm
							formLayout={{
								labelCol: {flex: '90px'},
								wrapperCol: {flex: '1'},
							}}
							formItems={FormItems}
							onReset={() => {
								setSearchData({})
								setMangerPagination({
									current: 1,
									pageSize: 10,
								})
							}}
							onFinish={(value) => {
								setSearchData(value)
								setMangerPagination({
									current: 1,
									pageSize: 10,
								})
							}}
						/>
					</div>
					<div className="content">
						<Table
							columns={ManagerColnums}
							rowKey="id"
							dataSource={mangerDataList}
							loading={mangerLoading}
							pagination={false}
							rowSelection={{
								type: 'radio',
								onChange: (
									selectedRowKeys: React.Key[],
									selectedRows: any[],
								) => {
									setMangerSelectedRow(selectedRows[0])
								},
							}}
						/>
						<div className="pagination">
							<Pagination
								pageSizeOptions={[10, 20]}
								defaultCurrent={1}
								current={mangerPagination.current}
								total={mangertotal}
								showTotal={(t, range) =>
									`第  ${range[0]} - ${range[1]} 条 / 总共 ${t} 条`
								}
								showSizeChanger
								showQuickJumper
								onChange={(
									current: number,
									pageSize: number,
								) => {
									setMangerPagination({
										current,
										pageSize,
									})
								}}
							/>
						</div>
					</div>
				</div>
			</Modal>
			<Modal
				// eslint-disable-next-line prefer-template
				title={OperationDriverMap[operationDriver] + '司机'}
				open={driverModalVisivle}
				onCancel={() => {
					setMangerPagination({
						current: 1,
						pageSize: 10,
					})
					setPagination({
						current: 1,
						pageSize: 10,
					})
					setdriverModalVisivle(false)
				}}
				width={1000}
				onOk={onSave}
				okButtonProps={{loading: saveLoading}}
				destroyOnClose
				zIndex={1}>
				<div className="addVehicleInfo">
					<div className="searchBox">
						<SearchForm
							formLayout={{
								labelCol: {flex: '90px'},
								wrapperCol: {flex: '1'},
							}}
							formItems={FleetFormItems}
							onReset={() => {
								setFormData({})
								getData()
							}}
							onFinish={(value) => {
								setFormData(value)
								getData({
									...value,
									...{
										current: 1,
										size: pagination.pageSize,
									},
								})
								setPagination({
									current: 1,
									pageSize: 10,
								})
							}}
						/>
					</div>
					<div className="content">
						<div className="select">
							已选择{selectedRow.length || 0}位司机
						</div>
						<Table
							columns={Cloums}
							rowKey="driverId"
							dataSource={dataList}
							loading={loading}
							rowSelection={{
								type: 'checkbox',
								onChange: (
									selectedRowKeys: React.Key[],
									selectedRows: any[],
								) => {
									setSelectedKeys(selectedRowKeys)
									setSelectedRow(selectedRows)
								},
								selectedRowKeys: selectedKeys,
							}}
							scroll={{x: 1500, y: 400}}
							pagination={false}
						/>
						<div className="pagination">
							<Pagination
								pageSizeOptions={[10, 20]}
								defaultCurrent={1}
								current={pagination.current}
								total={total}
								showTotal={(total1, range) =>
									`第  ${range[0]} - ${range[1]} 条 / 总共 ${total1} 条`
								}
								showSizeChanger
								showQuickJumper
								onChange={paginationChange}
							/>
						</div>
						{operationDriver === OperationDriverType.Transfer && (
							<div className="driverModalForm">
								<Form
									layout="horizontal"
									labelCol={{flex: '140px'}}
									labelAlign="right"
									labelWrap
									autoComplete="off"
									name="PersonalInformationFom"
									form={dirverModalForm}>
									<Form.Item
										label="迁移司管员"
										name="name"
										rules={[{required: true}]}>
										<Input
											onClick={() => setVisible(true)}
											placeholder="选择司管员"
										/>
									</Form.Item>
									<Form.Item label="司管员id" name="id">
										<Input placeholder="" disabled />
									</Form.Item>
								</Form>
							</div>
						)}
					</div>
				</div>
			</Modal>
		</div>
	)
}

export default driverModal
